#!/usr/bin/env python3
# coding=utf-8

import cv2
import numpy as np
import matplotlib.pyplot as plt


def mean_filter(img, name):
    # 均值平滑
    img_ret1 = cv2.blur(img, (3, 3))
    img_ret2 = cv2.blur(img, (7, 7))
    img_ret3 = cv2.blur(img, (11, 11))

    cv2.imwrite('tmp/filter_' + name + '_lena_mean_3.jpg', img_ret1)
    cv2.imwrite('tmp/filter_' + name + '_lena_mean_7.jpg', img_ret2)
    cv2.imwrite('tmp/filter_' + name + '_lena_mean_11.jpg', img_ret3)

    X = np.arange(img.shape[1])
    Y = img[10, :]  # 仅提取b通道第10行
    Y1 = img_ret1[10, :]  # 提取变化后图像的第10行
    Y2 = img_ret3[10, :]
    plt.plot(X, Y, '-g', label='raw image')  # 绘图
    plt.plot(X, Y1, '-r', label='blurred with 3')
    plt.plot(X, Y2, '-b', label='blurred with 11')
    plt.legend(title='gray value comparation on line 10',
               fontsize='xx-large', loc='upper center')
    plt.show()


def median_filter(img, name):
    # 中值平滑
    img_ret1 = cv2.medianBlur(img, 3)
    img_ret2 = cv2.medianBlur(img, 7)
    img_ret3 = cv2.medianBlur(img, 11)

    cv2.imwrite('tmp/filter_' + name + '_lena_median_3.jpg', img_ret1)
    cv2.imwrite('tmp/filter_' + name + '_lena_median_7.jpg', img_ret2)
    cv2.imwrite('tmp/filter_' + name + '_lena_median_11.jpg', img_ret3)


def gauss_filter(img, name):
    # 高斯平滑
    img_ret1 = cv2.GaussianBlur(img, (3, 3), 0)
    img_ret2 = cv2.GaussianBlur(img, (7, 7), 0)
    img_ret3 = cv2.GaussianBlur(img, (11, 11), 0)

    cv2.imwrite('tmp/filter_' + name + '_lena_gauss_3.jpg', img_ret1)
    cv2.imwrite('tmp/filter_' + name + '_lena_gauss_7.jpg', img_ret2)
    cv2.imwrite('tmp/filter_' + name + '_lena_gauss_11.jpg', img_ret3)

def bilateral_filter(img, name):
    # 双边滤波
    pass

if __name__ == "__main__":
    ifile1 = 'tmp/noised_lena_gaussian.jpg'
    ifile2 = 'tmp/noised_lena_sp.jpg'
    img1 = cv2.imread(ifile1, cv2.IMREAD_GRAYSCALE)
    img2 = cv2.imread(ifile2, cv2.IMREAD_GRAYSCALE)

    # mean_filter(img1, 'gauss')
    # mean_filter(img2, 'sp')
    # median_filter(img1, 'gauss')
    gauss_filter(img2, 'sp')
